import React, {useEffect, useState} from 'react'
import { Input, Button, Table, Modal, Row, Col, DatePicker, Divider } from 'antd'
import { connect } from 'umi'

const CreateMakeUpForm = (props) => {

  const [loading, setLoading] = useState(false);
  const { makeUpSubmit, onCancel, visible, operationType, current } = props;
  const [date, setDate] = useState(null);
  const [data, setData] = useState({});
  const [cacheOriginData, setCacheOriginData] = useState({});
  const [clickedCancel, setClickedCancel] = useState(false);

  useEffect(()=>{
    if (current && visible){
      setData(
        current.map((item, index) => {
          return {key: 'had' + index, ...item};
        })
      );
    }
  },[visible]);

  const onFormCancel = () => {
    onCancel()
  };

  const handleSubmit = async () => {
    makeUpSubmit(data,date)
  };

  const dateOnChange = (date, dateString) =>{
    setDate(date);
  };

  const columns = [
    {
      title: '姓名',
      align: 'center',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '参保地',
      align: 'center',
      dataIndex: 'cityName',
    },
    {
      title: '参保单位',
      align: 'center',
      dataIndex: 'unitName',
    },
    {
      title: '公积金',
      dataIndex: 'endowmentInsurancePerson',
      children: [
        {
          title: '个人',
          align: 'center',
          dataIndex: 'reservedFundsPerson',
          render: (text, record) => {
            if (record.editable) {
              return (
                <Input value={text==='-'?'':text} onChange={(e) => handleFieldChange(e, 'reservedFundsPerson', record.key)} />
              )
            }
            return text
          },
        },
        {
          title: '公司',
          align: 'center',
          dataIndex: 'reservedFundsOrg',
          render: (text, record) => {
            if (record.editable) {
              return (
                <Input value={text==='-'?'':text} onChange={(e) => handleFieldChange(e, 'reservedFundsOrg', record.key)} />
              )
            }
            return text
          },
        }
      ]
    },
    {
      title: '补充公积金',
      children: [
        {
          title: '个人',
          align: 'center',
          dataIndex: 'offerFundsPerson',
          render: (text, record) => {
            if (record.editable) {
              return (
                <Input value={text==='-'?'':text} onChange={(e) => handleFieldChange(e, 'offerFundsPerson', record.key)} />
              )
            }
            return text
          },
        },
        {
          title: '公司',
          align: 'center',
          dataIndex: 'offerFundsOrg',
          render: (text, record) => {
            if (record.editable) {
              return (
                <Input value={text==='-'?'':text} onChange={(e) => handleFieldChange(e, 'offerFundsOrg', record.key)} />
              )
            }
            return text
          },
        }
      ]
    },
    /*{
      title: '合计',
      fixed: 'right',
      width: 200,
      children: [
        {
          title: '个人',
          fixed: 'right',
          dataIndex: 'personCostTotal',
          hideInSearch: true,
          width: 100
        },
        {
          title: '公司',
          fixed: 'right',
          dataIndex: 'orgCostTotal',
          hideInSearch: true,
          width: 100
        },
      ]
    },*/
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      align: 'center',
      width: '150px',
      render: (text, record) => {
        if (!!record.editable && loading) {
          return null
        }
        if (record.editable) {
          return (
            <span>
              <a onClick={(e) => updateRow(e, record.key, record.oid)}>保存</a>
              <Divider type="vertical"/>
              <a onClick={(e) => cancel(e, record.key)}>取消</a>
            </span>
          )
        }
        return (
          <span>
            <a onClick={(e) => toggleEditable(e, record.key)}>编辑</a>
            <Divider type="vertical"/>
          </span>
        )
      },
    },
  ];

  const getRowByKey = (key, newData) => (newData || data)?.filter((item) => item.key === key)[0];

  const toggleEditable = (e, key, record) => {
    e.preventDefault();
    const newData = data?.map((item) => ({...item}));
    const target = getRowByKey(key, newData);
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        cacheOriginData[key] = {...target};
        setCacheOriginData(cacheOriginData)
      }
      target.editable = !target.editable;
      setData(newData)
    }
  };

  const handleFieldChange = (e, fieldName, key) => {
    const newData = [...data];
    const target = getRowByKey(key, newData);
    if (target) {
      target[fieldName] = e.target ? e.target.value : e;
      setData(newData)
    }
  }

  const updateRow = (e, rowKey) => {
    e.persist();
    if (clickedCancel) {
      setClickedCancel(false);
      return
    }
    toggleEditable(e, rowKey);
  }

  const cancel = (e, key) => {
    setClickedCancel(true);
    e.preventDefault();
    const newData = [...data]; // 编辑前的原始数据
    let cacheData = newData.map((item) => {
      if (item.key === key) {
        if (cacheOriginData[key]) {
          const originItem = {...item, ...cacheOriginData[key], editable: false};
          delete cacheOriginData[key];
          setCacheOriginData(cacheOriginData);
          return originItem
        }
      }
      return item
    });
    setData(cacheData);
    setClickedCancel(false)
  };

  const renderFooter = () => {
      return (
        <>
          <Button onClick={() => onFormCancel()}>取消</Button>
          {/*<Button type="primary" onClick={() => exportExcel()}>导出</Button>*/}
          <Button type="primary" onClick={() => handleSubmit()}>确认补缴</Button>
        </>
      )
  };

  return (
    <Modal
      width={'90%'}
      destroyOnClose
      title="补缴预览"
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
    >

      <Row>
        <Col style={{ paddingBottom: '24px' }}>
          请选择补缴月份：<DatePicker onChange={dateOnChange} picker="month" />
        </Col>
      </Row>

      <Table
        loading={loading}
        bordered
        pagination={false}
        rowKey="recordId"
        columns={columns}
        dataSource={data}
        // scroll={{y:500}}
      />

    </Modal>
  )
}


export default connect(({ user, personnel,global }) => ({
  global
}))(CreateMakeUpForm)
